package com.feeyo.groundservice.checkin.base

import com.feeyo.groundservice.base_util.FyLog
import com.feeyo.groundservice.checkin.constant.APPID
import com.feeyo.groundservice.checkin.constant.DEVICE
import com.feeyo.groundservice.checkin.constant.DS_ACCESS_TOKEN
import com.feeyo.groundservice.checkin.constant.DS_APPID
import com.feeyo.groundservice.checkin.constant.DS_DEVICE
import com.feeyo.groundservice.checkin.constant.DS_UID
import com.feeyo.groundservice.checkin.constant.token
import com.feeyo.groundservice.checkin.constant.uid
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

class MyOkhttpClient {
    companion object {
        private val outTime = 30L
        val client: OkHttpClient.Builder by lazy {
            val logInterceptor = HttpLoggingInterceptor()
            logInterceptor.level = HttpLoggingInterceptor.Level.BODY
            OkHttpClient.Builder()
                .addInterceptor(logInterceptor)
                .addInterceptor(HeaderTokenInterceptor())
                .retryOnConnectionFailure(false)
                .connectTimeout(outTime, TimeUnit.SECONDS)
                .readTimeout(outTime, TimeUnit.SECONDS)
                .writeTimeout(outTime, TimeUnit.SECONDS)
        }
    }


    /**
     * token验证
     * **/
    internal class HeaderTokenInterceptor : Interceptor {

        override fun intercept(chain: Interceptor.Chain): Response {
            val originRequest = chain.request()
            val builder = originRequest.newBuilder()
            val originUrl = originRequest.url.toString()

            val myHeaders = Headers.Builder().apply {
                add(DS_UID, uid)
                add(DS_ACCESS_TOKEN, token)
                add(DS_APPID, APPID)
                add(DS_DEVICE, DEVICE)
            }
            builder.headers(myHeaders.build())
            FyLog.e("值机请求的Url", originUrl)
            return chain.proceed(builder.build())
        }
    }
}